package cn.wolfcode.wolf2w.service.impl;

import cn.wolfcode.wolf2w.cache.vo.StrategyStatisVO;
import cn.wolfcode.wolf2w.domain.Destination;
import cn.wolfcode.wolf2w.domain.Strategy;
import cn.wolfcode.wolf2w.domain.StrategyCatalog;
import cn.wolfcode.wolf2w.domain.StrategyTheme;
import cn.wolfcode.wolf2w.query.QueryObject;
import cn.wolfcode.wolf2w.query.StrategyQueryObject;
import cn.wolfcode.wolf2w.repository.StrategyMongoRepository;
import cn.wolfcode.wolf2w.service.IDestinationService;
import cn.wolfcode.wolf2w.service.IStrategyCatalogService;
import cn.wolfcode.wolf2w.service.IStrategyService;
import cn.wolfcode.wolf2w.service.IStrategyThemeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.Date;
import java.util.List;

@Service
public class StrategyServiceImpl implements IStrategyService {
    
    @Autowired
    private StrategyMongoRepository strategyMongoRepository;

    @Autowired
    private MongoTemplate mongoTemplate;

    @Autowired
    private IStrategyCatalogService strategyCatalogService;

    @Autowired
    private IStrategyThemeService strategyThemeService;

    @Autowired
    private IDestinationService destinationService;


    @Override
    public void save(Strategy strategy) {
        strategy.setId(null);
        strategyMongoRepository.save(strategy);
    }

    @Override
    public void update(Strategy strategy) {
        strategyMongoRepository.save(strategy);
    }

    @Override
    public void delete(String id) {
        strategyMongoRepository.deleteById(id);
    }

    @Override
    public Strategy get(String id) {
        return strategyMongoRepository.findById(id).orElse(null);
    }

    @Override
    public List<Strategy> list() {
        return strategyMongoRepository.findAll();
    }

    @Override
    public Page<Strategy> query(QueryObject qo) {
        // 创建查询对象
        Query query = new Query();

        // 查询总条数
        long count = mongoTemplate.count(query, Strategy.class);
        // 调用PageRequest 方法进行分页
        Pageable pageable = PageRequest.of(qo.getCurrentPage() - 1, qo.getPageSize(), Sort.Direction.ASC, "_id");
        // 给查询对象设置条件
        query.with(pageable);
        // 从mongodb 中查询符合条件的数据
        List<Strategy> strategys = mongoTemplate.find(query, Strategy.class);
        // 返回当前页数据,分页和总长度
        return new PageImpl<>(strategys , pageable , count);
    }

    @Override
    public void saveOrUpdate(Strategy strategy) {
        // 1.目的地id
        // 通过当前攻略分类id catalogid 获取到所有攻略分类catalog
        StrategyCatalog catalogs = strategyCatalogService.get(strategy.getCatalogId());
        // 从所有攻略分类中获取所需要的的属性 destId
        String destId = catalogs.getDestId();
        // 把所需要的的属性set进strategy 中
        strategy.setDestId(destId);

        // 2.目的地name
        String destName = catalogs.getDestName();
        // 把所需要的属性set 进 strategy 中
        strategy.setDestName(destName);

        // 3.主题分类名称
        StrategyTheme strategyThemes = strategyThemeService.get(strategy.getThemeId());
        strategy.setThemeName(strategyThemes.getName());
        // 4.分类名称
        strategy.setCatalogName(catalogs.getName());
        // 5.是否国外
        List<Destination> toasts = destinationService.queryToasts(catalogs.getDestId());
        if(toasts != null && toasts.size() > 0 ){
            Destination dest = toasts.get(0);
            if("中国".equals(dest)){
                strategy.setIsabroad(Strategy.ABROAD_NO);
            }else {
                strategy.setIsabroad(Strategy.ABROAD_YES);
            }
        }

        if (StringUtils.hasLength(strategy.getId())){
            // 因为编辑操作时全量查询,所以要把所有字段都维护
            // 1. 查询当前id 下的所有字段
            Strategy temp = this.get(strategy.getId());
            // 先获取到当前对象的viewnum 字段 ,在设置进当前的对象中, 其他同理
            strategy.setViewnum(temp.getViewnum());
            strategy.setReplynum(temp.getReplynum());
            strategy.setFavornum(temp.getFavornum());
            strategy.setSharenum(temp.getSharenum());
            strategy.setThumbsupnum(temp.getThumbsupnum());

            strategy.setCreateTime(temp.getCreateTime());
            this.update(strategy);
        }else {
            // 6.创建时间
            strategy.setCreateTime(new Date());
            this.save(strategy);
        }
    }

    @Override
    public List<Strategy> queryCatalogId(String id) {
        List<Strategy> strategies = strategyMongoRepository.findByCatalogId(id);
        return strategies;
    }

    @Override
    public List<Strategy> queryViewnumTop3(String destId) {
        Query query = new Query();
        if(StringUtils.hasLength(destId)){
            query.addCriteria(Criteria.where("destId").is(destId));
        }


        Pageable pageable = PageRequest.of(0,3 , Sort.Direction.DESC , "viewnum");
        query.with(pageable);

        return mongoTemplate.find(query , Strategy.class);
    }

    @Override
    public Page<Strategy> queryByThemeId(StrategyQueryObject qo) {
        Query query = new Query();

        if(StringUtils.hasLength(qo.getThemeId())){
            query.addCriteria(Criteria.where("themeId").is(qo.getThemeId()));
        }
        Long count = mongoTemplate.count(query, Strategy.class);
        Pageable pageable = PageRequest.of(qo.getCurrentPage()-1 , qo.getPageSize() ,
                Sort.Direction.ASC , "_id");
        query.with(pageable);
        List<Strategy> strategies = mongoTemplate.find(query, Strategy.class);
        return  new PageImpl<>(strategies , pageable , count);


    }

    @Override
    public void updateVo(StrategyStatisVO vo) {
        // 创建一个查询方法
        Query query = new Query();
        // 在查询方法中添加一个条件
        query.addCriteria(Criteria.where("_id").is(vo.getStrategyId()));
        // 创建一个更新对象
        Update update = new Update();
        update.set("viewnum" , vo.getViewnum());
        update.set("replynum" , vo.getReplynum());
        update.set("favornum" , vo.getFavornum());
        update.set("sharnum" , vo.getSharnum());
        update.set("thumbsupnum" , vo.getThumbsupnum());
        // 把查询到符合更新条件的字段存入mongodb中
        mongoTemplate.updateMulti(query , update , Strategy.class);
    }

}
